package ckw.gui;

import java.util.ArrayList;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;

import ckw.database.DatabaseManager;
import ckw.database.OKW;
import ckw.database.Voter;
import ckw.database.VotersList;
import ckw.gui.wizards.WzdElectionDlgVotersListAdd;

import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.swt.graphics.Image;

import core.exceptions.ConnectionBetweenObjectsException;
import core.exceptions.NoConnectionBetweenObjectsException;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

public class DlgDbVoterAddEdit extends Dialog {
	private class TableLabelProvider extends LabelProvider implements
			ITableLabelProvider {
		public Image getColumnImage(Object element, int columnIndex) {
			return null;
		}

		public String getColumnText(Object element, int columnIndex) {
			VotersList votersList = (VotersList) element;
			return votersList.getName() + " - " + votersList.getDescription();
		}
	}

	private Text txtNazwa;
	private Text txtNazwisko;
	private Text txtAdres;
	private Text txtIdentyfikator;
	private Combo combo;
	private Table table;

	private Voter voter;
	private ArrayList<OKW> okwList;
	private int idxSelectedOKW;
	private ArrayList<VotersList> votersListList;

	private boolean edit;

	/**
	 * Create the dialog.
	 * 
	 * @param parentShell
	 */
	public DlgDbVoterAddEdit(Shell parentShell, Voter voter, boolean edit) {
		super(parentShell);

		this.voter = voter;
		this.edit = edit;

		this.okwList = (ArrayList<OKW>) DatabaseManager.getInstance().getAll(
				OKW.class);
		for (int i = 0; i < okwList.size(); i++) {
			OKW okw = okwList.get(i);
			okw = DatabaseManager.getInstance().get(OKW.class, okw.getId());
			okwList.set(i, okw);
		}
		this.votersListList = (ArrayList<VotersList>) DatabaseManager
				.getInstance().getAll(VotersList.class);
		for (int i = 0; i < votersListList.size(); i++) {
			VotersList votersList = votersListList.get(i);
			votersList = DatabaseManager.getInstance().get(VotersList.class,
					votersList.getId());
			votersListList.set(i, votersList);
		}

		if (edit) {
			OKW okw1 = voter.getOkw();
			okw1 = DatabaseManager.getInstance().get(OKW.class, okw1.getId());
			for (int i = 0; i < okwList.size(); i++) {
				OKW okw2 = okwList.get(i);
				if (okw1.getIdentificationField().compareTo(
						okw2.getIdentificationField()) == 0) {
					idxSelectedOKW = i;
					break;
				}
			}
		}
	}

	/**
	 * Create contents of the dialog.
	 * 
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		container.setLayout(new GridLayout(2, false));

		Label lblImie = new Label(container, SWT.NONE);
		lblImie.setText("Imie:");

		txtNazwa = new Text(container, SWT.BORDER);
		txtNazwa.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));
		txtNazwa.setText(!edit ? "" : voter.getName());

		Label lblNazwisko = new Label(container, SWT.NONE);
		lblNazwisko.setText("Nazwisko:");

		txtNazwisko = new Text(container, SWT.BORDER);
		txtNazwisko.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		txtNazwisko.setText(!edit ? "" : voter.getSurname());

		Label lblIdentyfikator = new Label(container, SWT.NONE);
		lblIdentyfikator.setText("Identyfikator:");

		txtIdentyfikator = new Text(container, SWT.BORDER);
		txtIdentyfikator.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		txtIdentyfikator.setText(!edit ? "" : voter.getIdentificationField());

		Label lblAdres = new Label(container, SWT.NONE);
		lblAdres.setText("Adres:");

		txtAdres = new Text(container, SWT.BORDER);
		txtAdres.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));
		txtAdres.setText(!edit ? "" : voter.getAddress());

		Label label = new Label(container, SWT.NONE);
		label.setText("OKW:");

		combo = new Combo(container, SWT.READ_ONLY);
		combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1,
				1));
		for (OKW okw : okwList) {
			combo.add(okw.getName() + " - " + okw.getIdentificationField());
		}
		if (edit) {
			combo.select(idxSelectedOKW);
		}

		Label lblLista = new Label(container, SWT.NONE);
		lblLista.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1,
				1));
		lblLista.setText("Lista:");

		final CheckboxTableViewer checkboxTableViewer = CheckboxTableViewer
				.newCheckList(container, SWT.BORDER | SWT.FULL_SELECTION);
		table = checkboxTableViewer.getTable();
		table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		new Label(container, SWT.NONE);
		
		Button btnAddList = new Button(container, SWT.NONE);
		btnAddList.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				VotersList votersList = new VotersList();
				WzdElectionDlgVotersListAdd dlg = new WzdElectionDlgVotersListAdd(getShell(), votersList, false);
				if (dlg.open() == IDialogConstants.OK_ID) {
					votersListList.add(votersList);
					checkboxTableViewer.add(votersList);
				}
			}
		});
		btnAddList.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		btnAddList.setText("Dodaj nowa liste");
		checkboxTableViewer.setLabelProvider(new TableLabelProvider());
		checkboxTableViewer.addCheckStateListener(new ICheckStateListener() {
			@Override
			public void checkStateChanged(CheckStateChangedEvent arg0) {
				((VotersList) arg0.getElement()).toggle();
			}
		});

		for (VotersList votersList : votersListList) {
			checkboxTableViewer.add(votersList);
			if (edit) {
				if (DatabaseManager.getInstance().voterOnVotersList(voter,
						votersList)) {
					checkboxTableViewer.setChecked(votersList, true);
					votersList.setChecked(true);
				}
			}
		}

		return container;
	}

	/**
	 * Create contents of the button bar.
	 * 
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, edit ? "Zapisz" : "Dodaj",
				true);
		createButton(parent, IDialogConstants.CANCEL_ID, "Anuluj", false);
	}

	/**
	 * Return the initial size of the dialog.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(450, 350);
	}

	protected void okPressed() {
		voter.setName(txtNazwa.getText());
		voter.setSurname(txtNazwisko.getText());
		voter.setIdentificationField(txtIdentyfikator.getText());
		voter.setAddress(txtAdres.getText());
		
		voter.setOkw(okwList.get(combo.getSelectionIndex()));
		if (!edit) {
			DatabaseManager.getInstance().save(voter);
		} else {
			DatabaseManager.getInstance().update(voter);
		}
		voter = DatabaseManager.getInstance().get(Voter.class, voter.getId());
		for(VotersList votersList : votersListList) {
			if(votersList.getChecked() == true) {
				try {
					DatabaseManager.getInstance().addVoterToVotersList(voter, votersList);
				} catch (ConnectionBetweenObjectsException e) {
				}
			} else {
				try {
					DatabaseManager.getInstance().removeVoterFromVotersList(voter, votersList);
				} catch (NoConnectionBetweenObjectsException e) {
				}
			}
		}	
		super.okPressed();
	}
}
